package ch89;
import java.math.BigInteger;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JRadioButton;

public class ElGamalMain {
    public static void main(String[] args) {
        new test();
    }
}
class test implements ActionListener {
    JFrame jf = new JFrame("ElGamal");
    JPanel panel = new JPanel();
    JRadioButton rb1 = new JRadioButton("加密");
    JRadioButton rb2 = new JRadioButton("解密");
    ButtonGroup group = new ButtonGroup();

    test() {
        jf.add(panel);
        group.add(rb1);
        group.add(rb2);
        panel.add(rb1);
        panel.add(rb2);
        rb1.addActionListener(this);
        rb2.addActionListener(this);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.setSize(300, 200);
        jf.setVisible(true);

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (group.getSelection() == rb1.getModel()) {
            String s1;
            s1 = JOptionPane.showInputDialog("请输入明文，将使用ElGamal算法进行加密.");
            BigInteger p = null; // 随机数 P
            BigInteger g = null; // P的生成元
            BigInteger b = null; // 公钥<b,g,p>
            BigInteger a = null;// 私钥<a> 0<a<p
            BigInteger[] rtn = { null, null };
            rtn = ElGamal.getRandomP(new BigInteger(s1.getBytes()).bitLength());
            BigInteger mingwen=new BigInteger(s1.getBytes());
            p = rtn[0];
            g = rtn[1];
            a = ElGamal.getRandoma(p);
            b = ElGamal.calculateb(g, a, p);
            rtn = ElGamal.encrypt(new BigInteger(s1.getBytes()), p, b, g);
            JOptionPane.showMessageDialog(null, "明文为：" +mingwen);
            JOptionPane.showMessageDialog(null, "加密结果为：" +rtn[0]+","+rtn[1]);
            JOptionPane.showMessageDialog(null, "密钥p为：" + p);
            JOptionPane.showMessageDialog(null, "私钥a为：" + a);
        }
        if (group.getSelection() == rb2.getModel()) {
            String s4,s3;
            JOptionPane.showInputDialog("将使用ElGamal算法进行解密.");
            String s1=JOptionPane.showInputDialog("请输入密文1:");
            String s2=JOptionPane.showInputDialog("请输入密文2:");
            s3= JOptionPane.showInputDialog("请输入密钥p");
            s4= JOptionPane.showInputDialog("请输入私钥a");
            BigInteger c1 =new BigInteger(s1) ;
            BigInteger c2 = new BigInteger(s2);
            BigInteger p =new BigInteger(s3);
            //BigInteger g = null; // P的生成元
            BigInteger a = new BigInteger(s4);
            //a = EIGamal.getRandoma(p);
            //BigInteger b = EIGamal.calculateb(g, a, p);
            BigInteger[] rtn = { c1,c2 };
            BigInteger dm = ElGamal.decrypt(rtn[0], rtn[1],a, p);
            JOptionPane.showMessageDialog(null, "解密结果为为：" + dm);
        }
    }
}
